# Preferences data and GUI
#
# Copyright (C) 2010 Yotam Medini <yotam.medini@gmail.com>
#
# This file is part of Gupicasa.
#
# Gupicasa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gupicasa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gupicasa.  If not, see <http://www.gnu.org/licenses/>.


import gtk

# local
import debug
import ped
import ugtk
import usys


class Preferences:


    def __init__(self, scratch_dir=None,
                 auto_clear=False,
                 mosaic_square=False,
                 mosaic_columns=10,
                 thumb_size_mm=(36,72)):
        if scratch_dir is None:
            scratch_dir = "/tmp/gupicasa-" + usys.myuname()
        self.scratch_dir = scratch_dir
        self.auto_clear = auto_clear
        self.mosaic_square = mosaic_square
        self.mosaic_columns = mosaic_columns
        self.thumb_size_mm = thumb_size_mm
        self.observers = []


    def mosaic_zcolumns(self):
        return 0 if self.mosaic_square else self.mosaic_columns


    def changed(self):
        debug.log("")
        for observer in self.observers:
            observer(self)


class PreferencesDialog(gtk.Dialog):

    def __init__(self, prefs, parent=None, icon=None):
        flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
        gtk.Dialog.__init__(self,
                            title="Gupicasa Preferences",
                            parent=parent, flags=flags,
                            buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
                                     gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        if icon is not None:
            self.set_icon(icon)
        self.prefs = prefs
        stock = gtk.image_new_from_stock(gtk.STOCK_PREFERENCES,
                                         gtk.ICON_SIZE_DIALOG)
        self.vbox.pack_start(stock, expand=False, fill=False, padding=6)
        frame = ugtk.FrameBWC("Scratch", 4, gtk.VBox())
        hb = gtk.HBox()
        lbl = gtk.Label("Directory:")
        hb.pack_start(lbl, expand=False, fill=False, padding=2)
        self.escrdir = e = gtk.Entry()
        e.set_text(prefs.scratch_dir)
        e.set_editable(False)
        hb.pack_start(e, expand=True, fill=True, padding=2)
        bb = ugtk.StockButton(gtk.STOCK_OPEN)
        bb.set_tooltip_text("Browse...")
        bb.connect('clicked', self.select_dir, icon)
        hb.pack_start(bb, expand=False, fill=False, padding=2)
        frame.c.pack_start(hb, expand=False, fill=False, padding=4)
        self.auto_clear = cb = gtk.CheckButton("Auto Clear")
        cb.set_tooltip_text("Clear scratch directory\n" +
                            "When opening local original directory\n" +
                            "or exiting")
        cb.set_active(prefs.auto_clear)
        frame.c.pack_start(cb, expand=False, fill=False, padding=2)
        self.vbox.pack_start(frame, padding=6)

        frame_t = ugtk.FrameBWC("Thumbs", 4, gtk.VBox())

        hbox = gtk.HBox()
        frame_tc = ugtk.FrameBWC("Table Layout", 2, hbox)
        hbox.set_border_width(2)
        self.mosaic_square = cb = gtk.CheckButton("Square like")
        cb.set_active(prefs.mosaic_square)
        cb.set_tooltip_text("""
Number of columns will be
near the square root of
the number of images
the table"""[1:])
        hbox.pack_start(cb, expand=False, fill=False, padding=12)
        h1 = gtk.HBox()
        h1.set_tooltip_text("Number of columns\n" +
                            "in thumbs tables")
        nc = gtk.Label("#-Columns")
        h1.pack_start(nc, expand=False, fill=False, padding=1)
        self.mosaic_columns = sb = ugtk.IntegerSpinButton(1, 100)
        sb.set_value(prefs.mosaic_columns)
        h1.pack_start(sb, expand=False, fill=False, padding=1)
        cb.connect('clicked', self.check_square, h1)
        h1.set_sensitive(not prefs.mosaic_square)
        hbox.pack_start(h1, expand=False, fill=False, padding=12)
        frame_t.c.pack_start(frame_tc, expand=False, fill=False, padding=6)

        hbox = gtk.HBox()
        frame_lts = ugtk.FrameBWC("Local Thumb Size", 4, hbox)
        frame_lts.set_tooltip_text("Scale local thumbs\n" +
                                   "into this range")
        hbox.set_border_width(4)
        self.thumb_mm = [None, None]
        for i in (0, 1):
            hb = gtk.HBox()
            lbl = gtk.Label(("Min", "Max")[i])
            hb.pack_start(lbl, expand=False, fill=False, padding=1)
            self.thumb_mm[i] = ugtk.IntegerSpinButton(20 + 20*i, 100 + 100*i)
            self.thumb_mm[i].set_value(prefs.thumb_size_mm[i])
            hb.pack_start(self.thumb_mm[i], expand=True, fill=True, padding=1)
            hbox.pack_start(hb, expand=True, fill=True, padding=6)
        frame_t.c.pack_start(frame_lts, padding=6)

        self.vbox.pack_start(frame_t, padding=6)

        self.error = gtk.Label("")
        self.vbox.pack_start(self.error, padding=6)
        self.show_all()


    # TODO: Should use general from ugtk
    def select_dir(self, w, icon):
        debug.log("")
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                   gtk.STOCK_OPEN, gtk.RESPONSE_OK)
        dlg = gtk.FileChooserDialog(
            title="Select scratch Directory",
            parent=self,
            action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            buttons=buttons)
        if icon is not None:
            dlg.set_icon(icon)
        response = dlg.run()
        debug.log("response=%d, e=%s" % (response, dlg.get_filename()))
        if response == gtk.RESPONSE_OK:
            self.escrdir.set_text(dlg.get_filename())
        dlg.destroy()


    def check_square(self, w, hbox_columns):
        f = w.get_active()
        hbox_columns.set_sensitive(not f)



    def ok(self):
        ret = True
        m = tuple(map(lambda s: s.get_value(), self.thumb_mm))
        debug.log("m=(%d,%d)" % m)
        if m[0] >= m[1]:
            t = "Thumb size: Min=%d >= Max=%d" % m
            self.error.set_markup('<span foreground="red">%s</span>' % t)
            ret = False
        else:
            self.error.set_text("")
        return ret


    def xrun(self):
        ok = False;
        response = gtk.RESPONSE_OK
        while not ok and response == gtk.RESPONSE_OK:
            response = self.run()
            ok = self.ok()
            debug.log("ok=%d, response=%d" % (ok, response))
        if response == gtk.RESPONSE_OK and ok:
            p = self.prefs
            p.scratch_dir = self.escrdir.get_text()
            p.auto_clear = self.auto_clear.get_active()
            p.mosaic_square = self.mosaic_square.get_active()
            p.mosaic_columns = self.mosaic_columns.iget_value()
            mm = map(lambda s: s.iget_value(), self.thumb_mm)
            p.thumb_size_mm = tuple(mm)
            p.changed()
        return ok


if __name__ == '__main__':
    import sys
    preferences = Preferences("/tmp/kkk")
    for i in range(3):
        debug.log("i=%d" % i)
        dlg = PreferencesDialog(preferences)
        ok = dlg.xrun()
        dlg.destroy()
    sys.exit(0)

